import { Request, Response } from "express";
import Order from "../models/Order"; // 你的订单模型
import Behavior from "../models/Behavior";
import moment from "moment";

export const getAnalysisData = async (req: any, res: any) => {
    let totalSales = 0;
    let dailySales = 0;
    let dailySalesComparison: string | number = 0;
    let weeklySalesComparison: string | number = 0;
    let dailySalesComparisonStatus = "up";
    let weeklySalesComparisonStatus = "up";
    let dailyViews = 0;
    let monthlyViews = 0;

    // 设置日期
    const today = moment().startOf("day");
    const yesterday = moment().subtract(1, "days").startOf("day");
    const lastWeekSameDay = moment().subtract(1, "weeks").startOf("day");

    try {
        // 统计总销售额
        const totalSalesResult = await Order.aggregate([
            {
                $match: { status: { $in: ['paid', 'finished'] } } // 只选择 status 为 'paid' 的文档
                // $match: { status: 'paid' } // 只选择 status 为 'paid' 的文档
            },
            {
                $group: {
                    _id: null, // 不根据任何字段分组
                    totalSales: { $sum: "$totalAmount" }, // 计算所有订单的totalAmount字段之和
                },
            },
        ]);

        // 检查结果是否存在并返回
        if (totalSalesResult.length > 0) {
            totalSales = totalSalesResult[0].totalSales.toFixed(2);
        } else {
            totalSales = 0; // 如果没有订单，返回 0
        }

        // 计算日销售额
        dailySales = parseFloat((await calculateSalesForDate(today)).toFixed(2));

        // 计算日同比
        const previousDaySales = parseFloat(
            (await calculateSalesForDate(yesterday)).toFixed(2)
        );
        dailySalesComparison =
            previousDaySales === 0
                ? "-"
                : parseFloat(
                    (
                        ((dailySales - previousDaySales) / previousDaySales) *
                        100
                    ).toFixed(0)
                );
        dailySalesComparisonStatus =
            typeof dailySalesComparison === "number" && dailySalesComparison >= 0
                ? "up"
                : "down";

        // 计算周同比
        const lastWeekSales = parseFloat(
            (await calculateSalesForDate(lastWeekSameDay)).toFixed(2)
        );
        weeklySalesComparison =
            lastWeekSales === 0
                ? "-"
                : parseFloat(
                    (((dailySales - lastWeekSales) / lastWeekSales) * 100).toFixed(0)
                );
        weeklySalesComparisonStatus =
            typeof weeklySalesComparison === "number" && weeklySalesComparison >= 0
                ? "up"
                : "down";

        // 计算当天的访问量
        dailyViews = await Behavior.countDocuments({
            timestamp: {
                $gte: today.toDate(),
                $lt: moment(today).add(1, "days").toDate(),
            },
        });

        // 按天聚合过去一个月的访问量

        // 获取过去30天的日期列表
        const viewsDataDates = [];
        for (let i = 0; i < 30; i++) {
            viewsDataDates.push(moment().subtract(i, 'days').format('YYYY-MM-DD'));
        }
        viewsDataDates.reverse(); // 确保日期是从早到晚的顺序
        // 按天聚合过去30天的访问量
        const monthlyViewsData = await Behavior.aggregate([
            {
                $match: {
                    timestamp: {
                        $gte: moment().subtract(29, "days").startOf("day").toDate(),
                        $lt: moment().add(1, 'days').startOf("day").toDate()
                    }
                }
            },
            {
                $group: {
                    _id: { $dateToString: { format: "%Y-%m-%d", date: "$timestamp" } },
                    count: { $sum: 1 }
                }
            }
        ]);

        // 创建一个字典以快速访问日期对应的数据
        const dataMap = monthlyViewsData.reduce((map, obj) => {
            map[obj._id] = obj.count;
            return map;
        }, {});

        // 准备 ECharts 数据
        const viewsDataSeriesData = viewsDataDates.map(viewsDataDate => dataMap[viewsDataDate] || 0); // 如果某天没有数据，则默认为0
        const totalViews = viewsDataSeriesData.reduce((sum, current) => sum + current, 0); // 计算总访问量

        // 获取订单总数
        const totalOrder = await Order.countDocuments();

        // 获取过去30天的日期列表
        const orderDates = [];
        for (let i = 0; i < 30; i++) {
            orderDates.push(moment().subtract(i, 'days').format('YYYY-MM-DD'));
        }
        orderDates.reverse();

        // 按天聚合过去30天的订单数据
        const monthlyOrderData = await Order.aggregate([
            {
                $match: {
                    createdAt: {
                        $gte: moment().subtract(29, "days").startOf("day").format('YYYY-MM-DD'),
                        $lt: moment().add(1, 'days').startOf("day").format('YYYY-MM-DD')
                    }
                }
            },
            {
                $group: {
                    _id: { $dateToString: { format: "%Y-%m-%d", date: { $toDate: "$createdAt" } } },
                    count: { $sum: 1 }
                }
            }
        ]);

        // 创建一个字典以快速访问日期对应的订单数量
        const orderDataMap = monthlyOrderData.reduce((map, obj) => {
            map[obj._id] = obj.count;
            return map;
        }, {});

        // 准备每天的订单数量
        const dailyOrderData = orderDates.map(orderDate => orderDataMap[orderDate] || 0);

        // 计算转化率
        const conversionRate = totalOrder === 0 ? 0 : parseFloat(((totalOrder / totalViews) * 100).toFixed(2));


        res.status(200).json({
            status: "ok",
            data: {
                salesData: {
                    totalSales,
                    dailySales,
                    dailySalesComparison,
                    dailySalesComparisonStatus,
                    weeklySalesComparison,
                    weeklySalesComparisonStatus,
                },
                viewsData: {
                    dailyViews,
                    viewsDataCategories: viewsDataDates,
                    viewsDataSeriesData,
                    totalViews: totalViews
                },
                payData: {
                    totalOrder,
                    orderCategories: orderDates,
                    orderSeriesData: dailyOrderData,
                    conversionRate
                }
            },
        });
    } catch (error: any) {
        // console.error("Error in getAnalysisData:", error);
        // throw error; // 将错误向上抛出
        res.status(500).json({
            status: "false",
            message: "查询分析数据失败！",
            data: error.message,
        });
    }
};

/**
 * 计算指定日期的销售额
 */
const calculateSalesForDate = async (date: moment.Moment) => {
    // 开始日期和结束日期的字符串表示
    const startDateString = date.format("YYYY-MM-DD") + " 00:00:00";
    const endDateString =
        date.clone().add(1, "days").format("YYYY-MM-DD") + " 00:00:00";

    const sales = await Order.aggregate([
        {
            $match: {
                createdAt: {
                    $gte: startDateString,
                    $lt: endDateString,
                },
            },
        },
        {
            $group: {
                _id: null,
                totalSales: { $sum: "$totalAmount" },
            },
        },
    ]);

    console.log("sales:", sales);

    return sales.length > 0 ? sales[0].totalSales : 0;
};
